package com.gobang.common.exception;

import com.gobang.common.constant.BusinessErrorCode;
import com.gobang.domain.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * 
 * 统一处理系统中的各类异常，返回标准格式的错误信息
 * 
 * @author Gobang Team
 * @version 1.0.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleBusinessException(BusinessException e) {
        log.error("业务异常: code={}, message={}", e.getCode(), e.getMessage(), e);
        Integer code = e.getCode() != null ? e.getCode() : BusinessErrorCode.SYSTEM_ERROR.getCode();
        String message = e.getMessage() != null ? e.getMessage() : BusinessErrorCode.SYSTEM_ERROR.getMessage();
        return Result.fail(code, message);
    }

    /**
     * 处理基础异常
     */
    @ExceptionHandler(BaseException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleBaseException(BaseException e) {
        log.error("系统异常: code={}, message={}", e.getCode(), e.getMessage(), e);
        Integer code = e.getCode() != null ? e.getCode() : BusinessErrorCode.SYSTEM_ERROR.getCode();
        String message = e.getMessage() != null ? e.getMessage() : BusinessErrorCode.SYSTEM_ERROR.getMessage();
        return Result.fail(code, message);
    }

    /**
     * 处理参数校验异常（@Valid 注解）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数校验异常: {}", e.getMessage());
        String errorMessage = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining("; "));
        return Result.fail(BusinessErrorCode.PARAM_INVALID.getCode(), errorMessage);
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleBindException(BindException e) {
        log.error("参数绑定异常: {}", e.getMessage());
        String errorMessage = e.getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining("; "));
        return Result.fail(BusinessErrorCode.PARAM_INVALID.getCode(), errorMessage);
    }

    /**
     * 处理约束违反异常（@Validated 注解）
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleConstraintViolationException(ConstraintViolationException e) {
        log.error("约束违反异常: {}", e.getMessage());
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        String errorMessage = violations.stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining("; "));
        return Result.fail(BusinessErrorCode.PARAM_INVALID.getCode(), errorMessage);
    }

    /**
     * 处理缺少请求参数异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("缺少请求参数: {}", e.getMessage());
        String message = String.format("缺少必需参数: %s", e.getParameterName());
        return Result.fail(BusinessErrorCode.PARAM_MISSING.getCode(), message);
    }

    /**
     * 处理参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        log.error("参数类型不匹配: {}", e.getMessage());
        String message = String.format("参数 '%s' 类型不正确", e.getName());
        return Result.fail(BusinessErrorCode.PARAM_INVALID.getCode(), message);
    }

    /**
     * 处理请求体不可读异常
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("请求体不可读: {}", e.getMessage());
        return Result.fail(BusinessErrorCode.REQUEST_NOT_READABLE.getCode(), 
                BusinessErrorCode.REQUEST_NOT_READABLE.getMessage());
    }

    /**
     * 处理请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("请求方法不支持: {}", e.getMessage());
        return Result.fail(BusinessErrorCode.REQUEST_METHOD_NOT_SUPPORTED.getCode(), 
                BusinessErrorCode.REQUEST_METHOD_NOT_SUPPORTED.getMessage());
    }

    /**
     * 处理资源未找到异常
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleNoHandlerFoundException(NoHandlerFoundException e) {
        log.error("资源未找到: {}", e.getMessage());
        return Result.fail(BusinessErrorCode.RESOURCE_NOT_FOUND.getCode(), 
                BusinessErrorCode.RESOURCE_NOT_FOUND.getMessage());
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleNullPointerException(NullPointerException e) {
        log.error("空指针异常: ", e);
        return Result.fail(BusinessErrorCode.SYSTEM_ERROR.getCode(), "系统内部错误");
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleIllegalArgumentException(IllegalArgumentException e) {
        log.error("非法参数异常: {}", e.getMessage());
        return Result.fail(BusinessErrorCode.PARAM_INVALID.getCode(), e.getMessage());
    }

    /**
     * 处理非法状态异常
     */
    @ExceptionHandler(IllegalStateException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleIllegalStateException(IllegalStateException e) {
        log.error("非法状态异常: {}", e.getMessage());
        return Result.fail(BusinessErrorCode.SYSTEM_ERROR.getCode(), e.getMessage());
    }

    /**
     * 资源找不到
     */
    @ExceptionHandler(NoResourceFoundException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleNoResourceFoundException(NoResourceFoundException exception){
        log.error("找不到访问路径: {}对应资源",exception.getResourcePath());
        return Result.fail(BusinessErrorCode.RESOURCE_NOT_FOUND.getCode(), exception.getMessage());
    }


    /**
     * 处理其他未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<?> handleException(Exception e) {
        log.error("系统未知异常: ", e);
        return Result.fail(BusinessErrorCode.SYSTEM_ERROR.getCode(), 
                BusinessErrorCode.SYSTEM_ERROR.getMessage());
    }

}

